package controller

import (
	"encoding/json"
	"ez/apps/core/auto/controller"
	core "ez/apps/core/document"
	"ez/apps/core/service"
	"ez/config/r"
	"ez/custom/cc"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
)

type MenuController struct {
	controller.MenuAutoController
}

func init() {
	c := &MenuController{}
	ez.CreateApi(r.AdminGet("Menu"), c.GetAction)
	ez.CreateApi(r.AdminList("Menu"), c.ListAction)
	ez.CreateApi(r.AdminSave("Menu"), c.SaveAction)
	ez.CreateApi(r.AdminCopy("Menu"), c.CopyAction)
	ez.CreateApi(r.AdminTree("Menu"), c.TreeAction)
	ez.CreateApi(r.AdminUpdate("Menu"), c.UpdateAction)
	ez.CreateApi(r.AdminChoice("Menu"), c.ChoiceAction)
	ez.CreateApi(r.AdminDelete("Menu"), c.DeleteAction)
	ez.CreateApi(r.AdminUnDelete("Menu"), c.UnDeleteAction)
	ez.CreateApi(r.AdminDestroy("Menu"), c.DestroyAction)
	ez.CreateApi(r.AdminUpdateMany("Menu"), c.UpdateManyAction)
	ez.CreateApi(r.AdminDeleteMany("Menu"), c.DeleteManyAction)
	ez.CreateApi(r.AdminDestroyMany("Menu"), c.DestroyManyAction)

	ez.CreateApi(r.AdminApi("/Menu/my"), c.MyAction)
	ez.CreateApi(r.AdminApi("/Menu/import"), c.ImportAction)
	ez.CreateApi(r.AdminApi("/Menu/export"), c.ExportAction)
}

// func (c MenuController) AccessControl(session *ez.Session) { /* 在这里面重构 */ }
// func (c MenuController) GetAction(session *ez.Session) { /* 在这里面重构 */ }
// func (c MenuController) ListAction(session *ez.Session) { /* 在这里面重构 */ }
func (c MenuController) ImportAction(session *ez.Session) {
	this := cc.New(session)
	content := this.Get("content").IsString()
	list := make([]*core.Menu, 0)
	if this.Try(json.Unmarshal([]byte(content), &list)) {
		return
	}
	crud := core.NewMenuCrud(session)
	count := [2]int{len(list), 0}
	for _, menu := range list {
		//查重
		find, _ := crud.FindOneBy(ss.M{"url": menu.Url}, nil)
		if find.Id == 0 {
			find.Url = menu.Url
			find.Name = menu.Name
			find.Icon = menu.Icon
			find.Sort = menu.Sort
			find.Save()
			count[1]++
		}
	}
	core.MenuTreeModel{}.UpdateLeftAndRight(0, 0, 0)
	this.ReturnSuccess("OK", count)
}
func (c MenuController) ExportAction(session *ez.Session) {
	this := cc.New(session)
	root := this.Get("id").IsInt64()
	crud := core.NewMenuCrud(session)
	find, e := crud.FindId(root)
	if this.Try(e) {
		return
	}
	list, e := crud.FindBy(ss.M{"l__gte": find.L, "r__lte": find.R}, nil, 1, 0)
	if this.Try(e) {
		return
	}
	content, e := json.MarshalIndent(list, "", "\t")
	this.ReturnSuccess("OK", string(content))
}
func (c MenuController) MyAction(session *ez.Session) {
	/* 在这里面重构 */
	this := cc.New(session)
	uid := this.GetUserId()
	menus, e := service.GetMyMenu(uid)
	if this.Try(e) {
		return
	}
	this.ReturnSuccess("OK", menus)
}
